#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
飞书多维表格API使用示例
"""

import json
import time
import uuid
from feishu_bitable_client import FeishuBitableClient
from config import Config

def main():
    """主函数"""
    print("🚀 飞书多维表格API客户端示例")
    print("=" * 50)
    
    # 从配置文件加载应用信息
    config = Config()
    
    # 创建客户端
    client = FeishuBitableClient(
        client_id=config.CLIENT_ID,
        client_secret=config.CLIENT_SECRET
    )
    
    # 确保有有效的访问令牌
    print("\n🔐 正在获取访问令牌...")
    if not client.ensure_valid_token():
        print("❌ 无法获取访问令牌，请检查配置")
        return
    
    print("✅ 成功获取访问令牌")
    app_token = config.APP_TOKEN
    table_id = config.TABLE_ID
    view_id = config.VIEW_ID
    
    print(f"正在从config读取app_token和table_id，app_token: {app_token}, table_id: {table_id}, view_id: {view_id}")
    
    if not app_token or not table_id:
        print("❌ app_token和table_id不能为空")
        return
    
    # 示例操作菜单
    while True:
        print("\n" + "=" * 50)
        print("📋 请选择要执行的操作：")
        print("1. 搜索记录")
        print("2. 创建记录")
        print("3. 批量获取记录")
        print("4. 更新记录")
        print("5. 删除记录")
        print("6. 创建字段")
        print("7. 列出所有字段")
        print("8. 更新字段")
        print("9. 删除字段")
        print("0. 退出")
        
        choice = input("\n请输入选项 (0-9): ").strip()
        
        try:
            if choice == '0':
                print("👋 再见！")
                break
            elif choice == '1':
                search_records_example(client, app_token, table_id)
            elif choice == '2':
                create_record_example(client, app_token, table_id)
            elif choice == '3':
                get_records_example(client, app_token, table_id)
            elif choice == '4':
                update_record_example(client, app_token, table_id)
            elif choice == '5':
                delete_record_example(client, app_token, table_id)
            elif choice == '6':
                create_field_example(client, app_token, table_id)
            elif choice == '7':
                list_fields_example(client, app_token, table_id)
            elif choice == '8':
                update_field_example(client, app_token, table_id)
            elif choice == '9':
                delete_field_example(client, app_token, table_id)
            else:   
                print("❌ 无效选项，请重新选择")
                
        except Exception as e:
            print(f"❌ 操作失败: {e}")
        
        input("\n按回车键继续...")

def search_records_example(client: FeishuBitableClient, app_token: str, table_id: str):
    """搜索记录示例"""
    print("\n🔍 搜索记录")
    
    page_size = input("请输入每页记录数 (默认10): ").strip()
    page_size = int(page_size) if page_size.isdigit() else 10
    
    filter_condition = input("请输入过滤条件 (可选，直接回车跳过): ").strip()
    filter_condition = filter_condition if filter_condition else None
    
    print("\n正在搜索记录...")
    result = client.search_records(
        app_token=app_token,
        table_id=table_id,
        filter_condition=filter_condition,
        page_size=page_size
    )
    
    if result.get('code') == 0:
        records = result.get('data', {}).get('items', [])
        print(f"\n✅ 搜索成功，找到 {len(records)} 条记录：")
        for i, record in enumerate(records, 1):
            print(f"\n记录 {i}:")
            print(f"  ID: {record.get('record_id')}")
            print(f"  字段: {json.dumps(record.get('fields', {}), indent=4, ensure_ascii=False)}")
    else:
        print(f"❌ 搜索失败: {result}")

def create_record_example(client: FeishuBitableClient, app_token: str, table_id: str):
    """创建记录示例"""
    print("\n➕ 创建记录")
    print("请输入记录字段（JSON格式），例如: {\"字段名\": \"字段值\"}")
    
    fields_input = input("字段数据: ").strip()
    
    try:
        fields = json.loads(fields_input)
    except json.JSONDecodeError:
        print("❌ 无效的JSON格式")
        return
    
    print("\n正在创建记录...")
    result = client.create_record(
        app_token=app_token,
        table_id=table_id,
        fields=fields
    )
    
    if result.get('code') == 0:
        record = result.get('data', {}).get('record', {})
        print(f"\n✅ 记录创建成功！")
        print(f"  记录ID: {record.get('record_id')}")
        print(f"  字段: {json.dumps(record.get('fields', {}), indent=4, ensure_ascii=False)}")
    else:
        print(f"❌ 创建失败: {result}")

def get_records_example(client: FeishuBitableClient, app_token: str, table_id: str):
    """批量获取记录示例"""
    print("\n📄 批量获取记录")
    
    record_ids_input = input("请输入记录ID列表（用逗号分隔）: ").strip()
    record_ids = [rid.strip() for rid in record_ids_input.split(',') if rid.strip()]
    
    if not record_ids:
        print("❌ 记录ID列表不能为空")
        return
    
    print(f"\n正在获取 {len(record_ids)} 条记录...")
    result = client.get_records(
        app_token=app_token,
        table_id=table_id,
        record_ids=record_ids
    )
    
    if result.get('code') == 0:
        records = result.get('data', {}).get('records', [])
        print(f"\n✅ 获取成功，返回 {len(records)} 条记录：")
        for i, record in enumerate(records, 1):
            print(f"\n记录 {i}:")
            print(f"  ID: {record.get('record_id')}")
            print(f"  字段: {json.dumps(record.get('fields', {}), indent=4, ensure_ascii=False)}")
    else:
        print(f"❌ 获取失败: {result}")

def update_record_example(client: FeishuBitableClient, app_token: str, table_id: str):
    """更新记录示例"""
    print("\n✏️ 更新记录")
    
    record_id = input("请输入要更新的记录ID: ").strip()
    if not record_id:
        print("❌ 记录ID不能为空")
        return
    
    print("请输入要更新的字段（JSON格式），例如: {\"字段名\": \"新值\"}")
    fields_input = input("字段数据: ").strip()
    
    try:
        fields = json.loads(fields_input)
    except json.JSONDecodeError:
        print("❌ 无效的JSON格式")
        return
    
    print("\n正在更新记录...")
    result = client.update_record(
        app_token=app_token,
        table_id=table_id,
        record_id=record_id,
        fields=fields
    )
    
    if result.get('code') == 0:
        record = result.get('data', {}).get('record', {})
        print(f"\n✅ 记录更新成功！")
        print(f"  记录ID: {record.get('record_id')}")
        print(f"  字段: {json.dumps(record.get('fields', {}), indent=4, ensure_ascii=False)}")
    else:
        print(f"❌ 更新失败: {result}")

def delete_record_example(client: FeishuBitableClient, app_token: str, table_id: str):
    """删除记录示例"""
    print("\n🗑️ 删除记录")
    
    record_id = input("请输入要删除的记录ID: ").strip()
    if not record_id:
        print("❌ 记录ID不能为空")
        return
    
    confirm = input(f"确认要删除记录 {record_id} 吗？(y/N): ").strip().lower()
    if confirm != 'y':
        print("❌ 操作已取消")
        return
    
    print("\n正在删除记录...")
    result = client.delete_record(
        app_token=app_token,
        table_id=table_id,
        record_id=record_id
    )
    
    if result.get('code') == 0:
        print("\n✅ 记录删除成功！")
    else:
        print(f"❌ 删除失败: {result}")

def create_field_example(client: FeishuBitableClient, app_token: str, table_id: str):
    """新增字段示例"""
    print("\n➕ 新增字段")
    print("请输入字段定义（JSON格式），例如: {\"name\": \"新字段\", \"type\": 1}")
    
    field_def_input = input("字段定义: ").strip()
    
    try:
        field_def = json.loads(field_def_input)
    except json.JSONDecodeError:
        print("❌ 无效的JSON格式")
        return
    
    print("\n正在新增字段...")
    result = client.create_field(
        app_token=app_token,
        table_id=table_id,
        field_name=field_def['name'],
        field_type=field_def['type'],
        property=field_def.get('property'),
        description=field_def.get('description'),
        ui_type=field_def.get('ui_type'),
        client_token=str(uuid.uuid4())
    )
    
    if result.get('code') == 0:
        field_info = result.get('data', {}).get('field', {})
        print(f"\n✅ 字段新增成功！")
        print(f"  字段ID: {field_info.get('field_id')}")
        print(f"  字段名: {field_info.get('field_name')}")
    else:
        print(f"❌ 新增失败: {result}")
        return

def list_fields_example(client: FeishuBitableClient, app_token: str, table_id: str):
    """列出所有字段示例"""
    print("\n📋 列出所有字段")
    result = client.list_fields(
        app_token=app_token,
        table_id=table_id,
        page_size=50
    )
    
    if result.get('code') == 0:
        fields = result.get('data', {}).get('items', [])
        print(f"\n✅ 成功获取 {len(fields)} 个字段：")
        for field in fields:
            is_primary = '(主字段)' if field.get('is_primary') else ''
            print(f"  字段ID: {field.get('field_id')}")
            print(f"  字段名: {field.get('field_name')} {is_primary}")
            print(f"  字段类型: {field.get('type')}")
            print(f"  UI类型: {field.get('ui_type')}")
            description = field.get('description', {})
            if description and description.get('text'):
                print(f"  字段描述: {description.get('text')}")
            print("-" * 40)
    else:
        print(f"❌ 获取失败: {result}")
        
def update_field_example(client: FeishuBitableClient, app_token: str, table_id: str):
    """更新字段示例"""
    print("\n✏️ 更新字段")
    
    field_id = input("请输入要更新的字段ID: ").strip()
    if not field_id:
        print("❌ 字段ID不能为空")
        return
    
    print("请输入要更新的字段定义（JSON格式），例如: {\"name\": \"新字段名\", \"type\": 1}")
    field_def_input = input("字段定义: ").strip()
    
    try:
        field_def = json.loads(field_def_input)
    except json.JSONDecodeError:
        print("❌ 无效的JSON格式")
        return
    
    print("\n正在更新字段...")
    result = client.update_field(
        app_token=app_token,
        table_id=table_id,
        field_id=field_id,
        field_name=field_def.get('name'),
        field_type=field_def.get('type'),
        property=field_def.get('property'),
        description=field_def.get('description'),
        ui_type=field_def.get('ui_type')
    )
    
    if result.get('code') == 0:
        print("\n✅ 字段更新成功！")
    else:
        print(f"❌ 更新失败: {result}")

def delete_field_example(client: FeishuBitableClient, app_token: str, table_id: str):
    """删除字段示例"""
    print("\n🗑️ 删除字段")
    
    field_id = input("请输入要删除的字段ID: ").strip()
    if not field_id:
        print("❌ 字段ID不能为空")
        return
    
    confirm = input(f"确认要删除字段 {field_id} 吗？(y/N): ").strip().lower()
    if confirm != 'y':
        print("❌ 操作已取消")
        return
    
    print("\n正在删除字段...")
    result = client.delete_field(
        app_token=app_token,
        table_id=table_id,
        field_id=field_id
    )
    
    if result.get('code') == 0:
        print("\n✅ 字段删除成功！")
    else:
        print(f"❌ 删除失败: {result}")
        
if __name__ == "__main__":
    main()